package com.construction_Safety.leave.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.construction_Safety.information.domain.CInformation;
import com.construction_Safety.information.domain.CInspecAlbum;
import com.construction_Safety.leave.domain.CLeaveUser;
import com.construction_Safety.leave.service.ICLeaveUserService;
import com.construction_Safety.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.construction_Safety.common.annotation.Log;
import com.construction_Safety.common.core.controller.BaseController;
import com.construction_Safety.common.core.domain.AjaxResult;
import com.construction_Safety.common.enums.BusinessType;
import com.construction_Safety.leave.domain.CLeave;
import com.construction_Safety.leave.service.ICLeaveService;
import com.construction_Safety.common.utils.poi.ExcelUtil;
import com.construction_Safety.common.core.page.TableDataInfo;

/**
 * 请假信息管理Controller
 * 
 * @author yat
 * @date 2025-11-10
 */
@RestController
@RequestMapping("/leave/leave")
public class CLeaveController extends BaseController
{
    @Autowired
    private ICLeaveService cLeaveService;
    @Autowired
    private ICLeaveUserService cLeaveUserService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询请假信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:list')")
    @GetMapping("/list")
    public TableDataInfo list(CLeave cLeave,CLeaveUser cLeaveUser)
    {
//        // 先查询所有数据（不分页）
//        List<CLeave> allList = cLeaveService.selectCLeaveList(cLeave);
//        List<CLeaveUser> cLeaveUsers = cLeaveUserService.selectCLeaveUserList(cLeaveUser);
//
//        // 建立关联关系
//        Map<Long, CLeaveUser> leaveUserMap = cLeaveUsers.stream()
//                .collect(Collectors.toMap(CLeaveUser::getLeaveId, user -> user));
//
//        // 设置关联的 CLeaveUser
//        for (CLeave cleave : allList) {
//            CLeaveUser matchedUser = leaveUserMap.get(cleave.getId());
//            cleave.setcLeaveUser(matchedUser);
//        }
//        // 手动分页
//        System.out.println(allList);
//        return getDataTable(allList);
        startPage();
        List<CLeave> list = cLeaveService.selectCLeaveList(cLeave);
        List<CLeaveUser> cLeaveUsers = cLeaveUserService.selectCLeaveUserList(cLeaveUser);
        // 建立关联关系
        Map<Long, CLeaveUser> leaveUserMap = cLeaveUsers.stream()
                .collect(Collectors.toMap(CLeaveUser::getLeaveId, user -> user));

        // 设置关联的 CLeaveUser
        for (CLeave cleave : list) {
            CLeaveUser matchedUser = leaveUserMap.get(cleave.getId());
            cleave.setcLeaveUser(matchedUser);
        }
        return getDataTable(list);
    }

    /**
     * 导出请假信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:export')")
    @Log(title = "请假信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CLeave cLeave)
    {
        List<CLeave> list = cLeaveService.selectCLeaveList(cLeave);
        ExcelUtil<CLeave> util = new ExcelUtil<CLeave>(CLeave.class);
        util.exportExcel(response, list, "请假信息管理数据");
    }

    /**
     * 获取请假信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        CLeave cLeave = cLeaveService.selectCLeaveById(id);
        if (cLeave != null) {
            // 查询关联的员工信息
            CLeaveUser queryUser = new CLeaveUser();
            queryUser.setLeaveId(id);
            List<CLeaveUser> cLeaveUsers = cLeaveUserService.selectCLeaveUserList(queryUser);
            if (cLeaveUsers != null && !cLeaveUsers.isEmpty()) {
                cLeave.setcLeaveUser(cLeaveUsers.get(0));
            }
        }
        return success(cLeave);
    }

    /**
     * 新增请假信息管理
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:add')")
    @Log(title = "请假信息管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CLeave cLeave)
    {
        // 先插入请假信息，获取生成的ID
        int result = cLeaveService.insertCLeave(cLeave);
        if (result > 0 && cLeave.getId() != null) {
            CLeaveUser cLeaveUser = cLeave.getcLeaveUser();
            if (cLeaveUser != null && cLeaveUser.getUserId() != null) {
                // 设置关联的请假单ID
                cLeaveUser.setLeaveId(cLeave.getId());
                cLeaveUserService.insertCLeaveUser(cLeaveUser);
            }
        }
        return toAjax(result);
    }

    /**
     * 修改请假信息管理
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:edit')")
    @Log(title = "请假信息管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CLeave cLeave)
    {
        int result = cLeaveService.updateCLeave(cLeave);
        if (result > 0 && cLeave.getId() != null) {
            CLeaveUser cLeaveUser = cLeave.getcLeaveUser();
            if (cLeaveUser != null) {
                // 查询是否已存在关联的员工信息
                CLeaveUser queryUser = new CLeaveUser();
                queryUser.setLeaveId(cLeave.getId());
                List<CLeaveUser> existingUsers = cLeaveUserService.selectCLeaveUserList(queryUser);
                
                if (existingUsers != null && !existingUsers.isEmpty()) {
                    // 如果存在，更新
                    CLeaveUser existingUser = existingUsers.get(0);
                    if (cLeaveUser.getUserId() != null) {
                        existingUser.setUserId(cLeaveUser.getUserId());
                        cLeaveUserService.updateCLeaveUser(existingUser);
                    } else {
                        // 如果userId为空，删除关联
                        cLeaveUserService.deleteCLeaveUserById(existingUser.getId());
                    }
                } else {
                    // 如果不存在，新增
                    if (cLeaveUser.getUserId() != null) {
                        cLeaveUser.setLeaveId(cLeave.getId());
                        cLeaveUserService.insertCLeaveUser(cLeaveUser);
                    }
                }
            }
            // 注意：用户状态的更新改为通过定时任务处理，根据请假时间和销假时间自动更新
        }
        return toAjax(result);
    }

    /**
     * 删除请假信息管理
     */
    @PreAuthorize("@ss.hasPermi('leave:leave:remove')")
    @Log(title = "请假信息管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        // 先删除关联的员工信息
        for (Long id : ids) {
            CLeaveUser queryUser = new CLeaveUser();
            queryUser.setLeaveId(id);
            List<CLeaveUser> cLeaveUsers = cLeaveUserService.selectCLeaveUserList(queryUser);
            if (cLeaveUsers != null && !cLeaveUsers.isEmpty()) {
                for (CLeaveUser user : cLeaveUsers) {
                    cLeaveUserService.deleteCLeaveUserById(user.getId());
                }
            }
        }
        // 再删除请假信息
        return toAjax(cLeaveService.deleteCLeaveByIds(ids));
    }
}
